package com.guigu.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.common.base.Preconditions;
import com.guigu.domain.dto.AuthUserDTO;
import com.guigu.domain.dto.LoginRequestDTO;
import com.guigu.result.Result;
import com.guigu.service.AuthUserDomainService;
import com.guigu.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {


    @Resource
    private AuthUserDomainService authUserDomainService;

    @Resource
    private EmailService emailService;

    /**
     * 用户注册
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()), "邮箱不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getCode()), "验证码不能为空");
            return Result.ok(authUserDomainService.register(authUserDTO));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage());
            return Result.fail("注册用户失败：" + e.getMessage());
        }
    }

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    // 会话登录接口
    @PostMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestBody LoginRequestDTO loginRequest) {
        try {
            log.info("loginRequest-{}", loginRequest);
            Preconditions.checkArgument(!StringUtils.isBlank(loginRequest.getEmail()), "邮箱不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(loginRequest.getPassword()), "密码不能为空!");
            return Result.ok(authUserDomainService.doLogin(loginRequest.getEmail(), loginRequest.getPassword()));
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage());
            return Result.fail("用户登录失败：" + e.getMessage());
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }


    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @GetMapping("send-code")
    public Result<Boolean> sendCode(@RequestParam String email) {
        try {
            emailService.sendVerificationCode(email);
            return Result.ok();
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }



}
